import connection from '../../utils/db.js'
import requestCodes from '../../config/responseCodes.js'
import uuid from 'node-uuid'

// 统一处理返回结果
const handleSqlAction = function (err, result, res, req, reject) {
  if(err) {
    console.log('[SELECT ERROR] - ', err.message)
    reject(err.message || '请求出错')
  }
  res.send({
    code: requestCodes.success,
    message: '请求成功',
    data: result
  })
}

// 用户注册
export const handlerUserRegister = (req, res) => {
  const { name, pwd } = req.body
  if (!name) {
    throw '用户名不能为空'
  }
  if (!pwd) {
    throw '密码不能为空'
  }
  // 生成唯一用户id
  const userId = uuid.v1()
  const sql = `
    INSERT INTO user (username, pwd, id)
    SELECT '${name}', '${pwd}', '${userId}'
  `
  return new Promise((resolve, reject) => {
    connection.queryPool(sql, null, (err, result) => {
      handleSqlAction(err, result, res, req, reject)
    })
  })
}